package cn.tworice.client.web;

import cn.tworice.client.service.KeyExchangeService;
import cn.tworice.common.po.DistValue;
import cn.tworice.dist.service.DistValueService;
import cn.tworice.ip.util.IpAddrUtils;
import cn.tworice.log.annotation.Log;
import cn.tworice.client.service.ExchangeMessageService;
import cn.tworice.common.entity.code.*;
import cn.tworice.common.util.excel.InductsListener;
import cn.tworice.common.vo.*;
import cn.tworice.vo.SourceItem;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

import io.swagger.annotations.*;

import java.util.*;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/client/exchangeMessage")
@CrossOrigin
@Log(table = "exchange_message")
@Api(tags = "在线交流信息")
public class ExchangeMessageClient {
    @Autowired
    private ExchangeMessageService service;

    @Autowired
    private KeyExchangeService keyExchangeService;

    @GetMapping("list")
    @ApiOperation("获取分页列表")
    public RequestResult list(@RequestParam(required = false, defaultValue = "0")
                              @ApiParam("页码")
                              Integer page, @RequestParam(required = false, defaultValue = "100")
                              @ApiParam("每页数量")
                              Integer pageSize, @ApiParam("查询条件")
                              ExchangeMessage entity) {
        return RequestResult.success(201, "数据列表刷新成功")
                .appendData("list", service.list(page, pageSize, entity)).appendData("total", service.total(entity));
    }

    @GetMapping("message")
    @ApiOperation("获取聊天列表")
    public RequestResult message(@ApiParam("查询条件") ExchangeMessage entity) {

        return RequestResult.success(201, "数据列表刷新成功")
                .appendData("list", service.message(entity));
    }

    @GetMapping("chat")
    @ApiOperation("获取统计")
    public RequestResult chat(@ApiParam("查询条件") ExchangeMessage entity) {
        List<ExchangeMessage> message = service.message(entity);
        List<KeyExchange> list = keyExchangeService.list(0, 1000, new KeyExchange());

        Map<String, Integer> map = new HashMap<>();
        List<ExchangeMessage> messageList = new ArrayList<>();// 涉及关键词的聊天记录
        for (ExchangeMessage exchangeMessage : message) {
            for(KeyExchange keyExchange:list){
                // 如果聊天内容涉及到关键词
                if(exchangeMessage.getMessage().contains(keyExchange.getContent())){
                    messageList.add(exchangeMessage);
                    if(map.containsKey(keyExchange.getKeyType())){
                        map.put(keyExchange.getKeyType(), map.get(keyExchange.getKeyType()) + 1);
                    }else{
                        map.put(keyExchange.getKeyType(), 1);
                    }
                }
            }
        }
        List<SourceItem> sourceItemList = new ArrayList<>();
        for(String key:map.keySet()){
            SourceItem sourceItem = new SourceItem();
            sourceItem.setName(key);
            sourceItem.setValue(map.get(key).doubleValue());
            sourceItemList.add(sourceItem);
        }

        return RequestResult.success(201, "数据列表刷新成功")
                .appendData("chat", sourceItemList)
                .appendData("messageList",messageList);
    }

    @PostMapping("add")
    @ApiOperation("更新数据")
    public RequestResult add(ExchangeMessage entity, HttpServletRequest request) {
        entity.setIpaddr(IpAddrUtils.getIpAddr(request));
        service.set(entity);
        return RequestResult.success("更新数据成功")
                ;
    }

    @DeleteMapping("del")
    @ApiOperation("删除数据")
    public RequestResult del(@ApiParam("数据ID数组") Integer[] ids) {
        service.del(ids);
        return RequestResult.success("成功删除数据");
    }

    @PostMapping("inducts")
    @ApiOperation("Excel表格批量上传数据")
    public RequestResult inducts(@ApiParam("Excel文件")
                                 MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, ExchangeMessage.class, new InductsListener(service)).sheet().doRead();
            return RequestResult.success("批量导入数据成功")
                    ;
        } catch (Exception ex) {
            ex.printStackTrace();
            return RequestResult.error("批量导入数据失败")
                    ;
        }
    }

    /**
     * 导出模板     * @param response 结果     * @throws IOException 可能的IO异常
     */
    @GetMapping("template")
    @ApiOperation("导出Excel模板")
    public void template(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("模板", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExchangeMessage.class).sheet("模板")
                .doWrite(new ArrayList<>());
    }

    @GetMapping("info")
    @ApiOperation("获取数据")
    public RequestResult info(Integer id) {
        return RequestResult.success(201).appendData("info", service.info(id));
    }
}